package cn.com.callback
import groovy.json.JsonSlurper
import groovy.swing.impl.DefaultAction
import groovy.xml.Namespace
import java.text.MessageFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher
import java.util.regex.Pattern

import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import net.sf.json.JSONArray
import net.sf.json.JSONObject

import com.wisdge.dataservice.Result;
import cn.com.elite.Util;
import org.jdom.Document
import org.jdom.Element
import org.jdom.JDOMException
import org.jdom.input.SAXBuilder

public class WaterMeterService implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(WaterMeterService.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		log.debug("-------------------------start WaterMeterService-----------------");
		log.debug("request----------------:"+request);

		String getMethod = request.getMethod();
		String callJson="";
		BufferedReader iny = null;

		def reJson = "";

		log.debug("getMethod:"+getMethod);
		if (getMethod.equals("GET")) {
			callJson = request.getParameter("jsondata");
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				callJson += line;
			}
		}

		log.debug("callJson:"+callJson);
		try {

			//解析Json
			def rJson=new JsonSlurper().parseText(callJson);
			log.debug("rJson的信息:"+rJson);

			def userCode = "";//编码
			def startCostYearMonth = "";//开始时间
			def endCostYearMonth = "";//结束时间
			def payMentStatus = "";//状态

			log.debug("开始解析数据...");
			userCode = rJson.userCode;
			log.debug("传入的userCode:"+userCode);

			startCostYearMonth = rJson.startCostYearMonth;
			log.debug("传入的startCostYearMonth:"+startCostYearMonth);

			endCostYearMonth = rJson.endCostYearMonth;
			log.debug("传入的endCostYearMonth:"+endCostYearMonth);

			payMentStatus = rJson.payMentStatus;
			log.debug("传入的payMentStatus:"+payMentStatus);

			//开始调用xml接口
			def waterUrl = "http://138.0.0.96:7788/WaterMeterService.asmx";
			log.debug("调用的地址:"+waterUrl);
			def timeout=100000;
			def charset="utf-8";
			def xmlbody = """<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	<SOAP-ENV:Body>
		<m:GetComputeDetail xmlns:m="http://tempuri.org/">
			<m:userCode>"""+userCode+"""</m:userCode>
			<m:startCostYearMonth>"""+startCostYearMonth+"""</m:startCostYearMonth>
			<m:endCostYearMonth>"""+endCostYearMonth+"""</m:endCostYearMonth>
			<m:payMentStatus>"""+payMentStatus+"""</m:payMentStatus>
		</m:GetComputeDetail>
	</SOAP-ENV:Body>
</SOAP-ENV:Envelope>""";
			log.debug("调用的报文信息:"+xmlbody);

			try{
				//调用用户信息接口
				def xml = Util.callWebService(waterUrl,xmlbody,charset,'http://tempuri.org/GetComputeDetail',timeout);
				log.debug("处理前的xml:"+xml);
				xml = Util.Transform(xml); //去命令空间
				log.debug("返回的的xml:"+xml);

				//JSONObject json=xml2JSON(xml.getBytes());
				JSONObject json=xmlString2Json(xml);

				log.debug("当前处理xml转json...........");

				String s = json.toString();
				String a=s.replace('["', '"');
				String jsonList=a.replace('"]', '"');
				log.debug("处理后的json:"+jsonList);

				return "{\"code\":\"1\",\"msg\":\"执行成功\",\"detaillist\":"+jsonList+"}";
			}catch (Exception e){
				log.error("EM",e);
				return "{\"code\":\"-1\",\"msg\":\"执行失败"+e.getMessage()+"\"}";
			}

		} catch (Exception e) {
			log.error("异常信息",e);
			return "{\"code\":\"-1\",\"msg\":\"执行失败"+e.getMessage()+"\"}";
		}
	}
	//xmlStr转换成json
	def static JSONObject xmlString2Json(String xmlStr){
		JSONObject json = new JSONObject();
		try {
			InputStream is = new ByteArrayInputStream(xmlStr.getBytes("utf-8"));
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(is);
			Element root = doc.getRootElement();
			json.put(root.getName(), iterateElement(root));
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	//	public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
	//		JSONObject json = new JSONObject();
	//		InputStream is = new ByteArrayInputStream(xml);
	//		SAXBuilder sb = new SAXBuilder();
	//		Document doc = sb.build(is);
	//		System.out.print("doc"+doc);
	//		Element root = doc.getRootElement();
	//		json.put(root.getName(), iterateElement(root));
	//		return json;
	//	}


	private static JSONObject iterateElement(Element element) {
		List node = element.getChildren();
		Element et = null;
		JSONObject obj = new JSONObject();
		List list = null;
		for (int i = 0; i < node.size(); i++) {
			list = new LinkedList();
			et = (Element) node.get(i);

			if (et.getTextTrim().equals("")) {
				if (et.getChildren().size() == 0)
					continue;
				if (obj.containsKey(et.getName())) {
					list = (List) obj.get(et.getName());
				}
				list.add(iterateElement(et));
				obj.put(et.getName(), list);

			} else {
				if (obj.containsKey(et.getName())) {
					list = (List) obj.get(et.getName());
				}
				list.add(et.getTextTrim());
				obj.put(et.getName(), list);
			}

		}
		return obj;
	}

}
